import { Component, OnInit } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import {HttpClient,HttpHeaders} from "@angular/common/http";
import { ToastController } from '@ionic/angular';
import { AuthTokenService } from '@services/auth-token.service';
import { TranslateService } from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AutoLoginType } from '@services/common-service.service';
import { EncryptService } from '@services/encrypt.service';

@Component({
  selector: 'app-fingerprint-setup',
  templateUrl: './fingerprint-setup.page.html',
  styleUrls: ['./fingerprint-setup.page.scss'],
})
export class FingerprintSetupPage implements OnInit {

  public appUserId:string;
  public i18n:any;
  constructor(private router: Router,
              private route: ActivatedRoute,
              public http:HttpClient,
              private faio: FingerprintAIO,
              private toastController: ToastController,
              private authTokenService:AuthTokenService,
              private defaultLanguageService:DefaultLanguageService,
              private translate: TranslateService,
              private commonService:CommonService,
              public loadingController: LoadingController,
              private encryptService:EncryptService) {
    let defultLanguage = this.defaultLanguageService.getDefaultLanguage();
    this.translate.setDefaultLang(defultLanguage);
    this.translate.use(defultLanguage); 
    this.translate.get('auth.fingerprintSetup').subscribe((obj)=>{
      this.i18n = obj;
    });
  }

  ngOnInit() {
    this.route.queryParams.subscribe((data)=>{
      if(data.appUserId){
        this.appUserId = data.appUserId;
      }else{
        this.appUserId = this.authTokenService.getAppUserId();
      }
		})
  }

  skipSetup(){
    this.router.navigate(['/auth/signin-password']);
  }
  
  setupFingerprint(){
    this.faio.show({
        title: '',
        fallbackButtonTitle: 'Use Backup',
        disableBackup:true,
    }).then((result: any) => {
      if(result == "biometric_success"){
        this.enableFingerprint();
      }
    }).catch((error: any) => {
      console.log(error);
    });
  }

  async enableFingerprint(){
    const loading = await this.loadingController.create({
      cssClass: 'my-custom-class',
      message: 'Please wait...',

    });
    await loading.present();
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getAppUserId()+this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getAppUserId()+","+this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type':'application/json','sign1':sign1,'sign2':sign2 })
    };
    var api = "/scm/app/enableOrCloseAutoLogin.do";
    var requestJson = {
      'verificationType':VerificationType.SIGNUP,
      'autoLoginType':AutoLoginType.FINGER_PRINT,
      'appUserId':this.appUserId,
      'deviceId':this.authTokenService.getDeviceId(),
      'enable':true
    }
    this.http.post(api,requestJson,httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        this.commonService.commonToast(ToastColor.success,this.i18n.setup_success);
        this.authTokenService.setLoginToken(response.responseBody.loginToken);
        this.router.navigate(['/auth/signin-password']);
      }
      loading.dismiss();
    },(errorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      loading.dismiss();
    });
  }
}
